package com.smartrodin.springbootrabbitmq.util;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;

/**
 * 类名:IDGenerator
 * 功能:生产主键ID
 *
 * @author back
 * @version 1.0
 */
public class IDGenerator {

    private static final IDGenerator ID_GENNRATOR = new IDGenerator();
    private static final int THREAD_NUM = 2000;
    private static CountDownLatch cdl = new CountDownLatch( THREAD_NUM );

    private IDGenerator() {
    }

    public static IDGenerator getInstance() {
        return ID_GENNRATOR;
    }

    public static void main(String[] args) throws InterruptedException {
        IDGenerator generator = new IDGenerator();
        for (int i = 0; i < THREAD_NUM; i++) {
            new Thread( new Runnable() {
                @Override
                public void run() {
                    try {
                        cdl.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    generator.createInsertId();
                }
            } ).start();
            cdl.countDown();
        }
        Thread.sleep( 10000 );
    }

    /**
     * 生成一个32位的随机字符串
     *
     * @return
     */
    public String uuid() {
        return UUID.randomUUID().toString().replaceAll( "-", "" );
    }

    /**
     * 获取Long型逐渐ID
     *
     * @return
     */
    public String getId() {
        StringBuilder sb = new StringBuilder();
        sb.append( UUID.randomUUID().toString() ).append( System.nanoTime() );
        int id = sb.toString().hashCode();
        if (id < 0) {
            id = -id;
        }
        return String.valueOf( id );
    }

    public void createInsertId() {
        System.out.println( "insert into test_id(id)values('" + getId() + "');" );
    }
}